" CountMatches counts the number of times a pattern matches a
" range of lines
function! CountMatches(pattern, startline, endline) range
    let l:match_count = 0

    let l:restore_cursor = "normal!" . line(".") . "G" . virtcol(".") . "|"
    normal! H
    let l:restore_screen = line(".") . "normal!zt"

        " move cursor to 1st line of search range
    exec "normal!" . a:startline . "G0"
    
        " loop over the lines of the search range looking for pattern
    while 1
        let l:lnum = search(a:pattern, "W")

            " break loop if we are outside of the search range or we didn't
            " find a match (l:lnum == 0)
        if l:lnum > a:endline || l:lnum == 0
            break  
        endif  

        let l:match_count = l:match_count + 1
    endwhile

    exec l:restore_screen
    exec l:restore_cursor

        " tell the user how many matches we found
    echo "Pattern matched " . l:match_count . " times."
endfunction

" Define a command to call the above function
com! -range -nargs=1 CM call CountMatches("<args>", <line1>, <line2>)
